import pandas as pd
import requests
import math

class kfcstorelist:

    headers = {
        "accept": "application/json, text/javascript, */*; q=0.01",
        "accept-language": "zh-CN,zh;q=0.9",
        "cache-control": "no-cache",
        "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
        "origin": "https://www.kfc.com.cn",
        "pragma": "no-cache",
        "priority": "u=1, i",
        "referer": "https://www.kfc.com.cn/kfccda/storelist/index.aspx",
        "sec-ch-ua": "\"Google Chrome\";v=\"129\", \"Not=A?Brand\";v=\"8\", \"Chromium\";v=\"129\"",
        "sec-ch-ua-mobile": "?0",
        "sec-ch-ua-platform": "\"Windows\"",
        "sec-fetch-dest": "empty",
        "sec-fetch-mode": "cors",
        "sec-fetch-site": "same-origin",
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
        "x-requested-with": "XMLHttpRequest"
    }
    cookies = {
        "route-cell": "ksa",
        "ASP.NET_SessionId": "kge5lv2uh0d5k44rgojqz41g",
        "VOLCALB": "53748c9dc048804393377fdae8918c2f|1728712866|1728712747",
        "VOLCALBCORS": "53748c9dc048804393377fdae8918c2f|1728712866|1728712747"
    }
    url = "https://www.kfc.com.cn/kfccda/ashx/GetStoreList.ashx"
    params = {
        "op": "keyword"
    }
    data = {
        "cname": "深圳",
        "pid": "",
        "keyword": "深圳",
        "pageIndex": "1",
        "pageSize": "10"
    }

    @classmethod
    def get_store_lis(cls, page):
        cls.data['pageIndex'] = page
        response = requests.post(cls.url, headers=cls.headers, cookies=cls.cookies, params=cls.params, data=cls.data)
        return response.json()

    def parse_data(self, store_list):
        rowcount = store_list["Table"][0]['rowcount']
        # 检查文件是否存在，如果不存在，则写入表头
        try:
            with open("kfc_store.csv", "x"):
                pd.DataFrame(store_list['Table1']).to_csv("kfc_store.csv", encoding="utf-8")
        except FileExistsError:
            pd.DataFrame(store_list['Table1']).to_csv("kfc_store.csv", encoding="utf-8", mode='a', header=False, index=False)

    def run(self):
        response = self.get_store_lis(1)
        rowcount = response["Table"][0]['rowcount']
        # 创建一个只有表头的空表
        pd.DataFrame(columns=['rownum', 'storeName', 'addressDetail','pro']).to_csv("kfc_store.csv", encoding="utf-8",index=False)
        for i in range(1, math.ceil(rowcount / 10) + 1):
            self.parse_data(self.get_store_lis(i))

if __name__ == '__main__':
    kfc = kfcstorelist()
    kfc.run()